import { defineStore } from 'pinia'
import { studentApi } from '@/api'

export const useResumeStore = defineStore('resume', {
  state: () => ({
    profile: {
      firstName: '',
      lastName: '',
      name: '',
      avatar: '',
      nationality: '',
      gender: '',
      birthDate: '',
      city: '',
      country: '',
      phone: '',
      email: '',
      wechat: '',
      desiredPosition: '',
      resumeStatus: '',
      rejectionReason: '',
      lastUpdateTime: ''
    },
    education: [{
      school: '',
      major: '',
      degree: '',
      startDate: '',
      endDate: ''
    }],
    languages: [],
    skills: [],
    experience: '',
    personalAdvantages: ''
  }),

  getters: {
    // 检查基本信息是否完整
    isBasicInfoComplete: (state) => {
      return (state.profile.lastName && state.profile.firstName) || state.profile.name && 
             state.profile.gender && 
             state.profile.phone && 
             state.profile.email
    },

    // 检查教育经历是否完整
    isEducationComplete: (state) => {
      return state.education.length > 0 && 
             state.education.some(edu => edu.major && edu.degree)
    },

    // 检查简历是否完整
    isResumeComplete: (state) => {
      return ((state.profile.lastName && state.profile.firstName) || state.profile.name) && 
             state.education.length > 0 && 
             (state.languages.length > 0 || state.skills.length > 0)
    },

    // 获取简历数据用于保存
    getResumeData: (state) => {
      return {
        profile: { ...state.profile },
        education: [...state.education],
        languages: [...state.languages],
        skills: [...state.skills],
        experience: state.experience,
        personalAdvantages: state.personalAdvantages
      }
    },

    // 获取安全的教育经历数组
    getSafeEducation: (state) => {
      if (!state.education || state.education.length === 0) {
        return [{
          school: '',
          major: '',
          degree: '',
          startDate: '',
          endDate: ''
        }]
      }
      return state.education.map(edu => ({
        school: edu?.school || '',
        major: edu?.major || '',
        degree: edu?.degree || '',
        startDate: edu?.startDate || '',
        endDate: edu?.endDate || ''
      }))
    }
  },

  actions: {
    // 初始化简历数据
    async initResume() {
      try {
        const response = await studentApi.getResume()
        
        if (response.code === 200 && response.data) {
          const data = response.data
          
          // 日期格式转换函数
          const formatDate = (dateString) => {
            if (!dateString) return ''
            try {
              // 如果是Date对象或ISO字符串，转换为yyyy-MM-dd格式
              const date = new Date(dateString)
              if (isNaN(date.getTime())) return dateString
              return date.toISOString().split('T')[0]
            } catch (error) {
              return dateString
            }
          }

          // 映射后端数据到前端数据结构
          this.profile = {
            firstName: data.ming || '',
            lastName: data.xing || '',
            name: data.fullName || '',
            avatar: data.avatarUrl || '', // 使用后端返回的头像URL
            nationality: data.nationality || '',
            gender: data.gender === 'male' ? '男' : data.gender === 'female' ? '女' : data.gender === 'other' ? '其他' : data.gender || '',
            birthDate: formatDate(data.dateOfBirth),
            city: '',
            country: '',
            phone: data.phoneNumber || '',
            email: data.email || '',
            wechat: data.wechatWhatsapp || '',
            desiredPosition: '',
            resumeStatus: data.resumeStatus || '',
            rejectionReason: data.rejectionReason || '',
            lastUpdateTime: data.lastUpdateTime || ''
          }
          
          // 教育经历
          this.education = data.educationList && data.educationList.length > 0 
            ? data.educationList.map(edu => ({
                major: edu.major || '',
                degree: edu.degree || '',
                startDate: edu.startDate || '',
                endDate: edu.endDate || ''
              }))
            : [{
                major: '',
                degree: '',
                startDate: '',
                endDate: ''
              }]
          
          // 语言能力
          this.languages = data.languagesList ? data.languagesList.map(lang => lang.languageName) : []
          
          // 专业技能 - 修复：从skillsList中提取skillName
          this.skills = data.skillsList ? data.skillsList.map(skill => skill.skillName) : []
          
          // 工作经验（富文本内容）
          this.experience = data.resumeContent || ''
          
          // 个人优势
          this.personalAdvantages = ''
          
        } else if (response.code === 404) {
          // 新用户，简历数据不存在，这是正常状态
          // 确保初始化默认的教育经历
          this.education = [{
            school: '',
            major: '',
            degree: '',
            startDate: '',
            endDate: ''
          }]
          return // 直接返回，不抛出错误
        } else {
          // 其他错误
          throw new Error(response.message || '获取简历失败')
        }
      } catch (error) {
        // 如果API调用失败，尝试从localStorage获取数据作为备用
        const savedData = localStorage.getItem('resumeData')
        if (savedData) {
          try {
            const data = JSON.parse(savedData)
            this.profile = { ...this.profile, ...data.profile }
            this.education = data.education && data.education.length > 0 
              ? data.education.map(edu => ({
                  major: edu.major || '',
                  degree: edu.degree || '',
                  startDate: edu.startDate || '',
                  endDate: edu.endDate || ''
                }))
              : [{
                  major: '',
                  degree: '',
                  startDate: '',
                  endDate: ''
              }]
            this.languages = data.languages || []
            this.skills = data.skills || []
            this.experience = data.experience || ''
            this.personalAdvantages = data.personalAdvantages || ''
          } catch (e) {
            // 忽略本地数据加载错误
          }
        }
      }
    },

    // 保存简历数据
    async saveResume() {
      try {
        // 检查用户是否已登录
        const accessToken = localStorage.getItem('access_token');
        if (!accessToken) {
          return { 
            success: false, 
            message: '请先登录后再提交简历',
            code: 'AUTH_REQUIRED'
          };
        }

        // 数据验证
        const validationErrors = []
        // 检查姓名：要么填写姓和名，要么填写中文姓名
        if (!this.profile.lastName?.trim() && !this.profile.firstName?.trim() && !this.profile.name?.trim()) {
          validationErrors.push('请填写姓和名，或填写中文姓名')
        }
        if (!this.profile.gender?.trim()) {
          validationErrors.push('性别不能为空')
        }
        if (!this.profile.phone?.trim()) {
          validationErrors.push('电话号码不能为空')
        }
        if (!this.profile.email?.trim()) {
          validationErrors.push('邮箱不能为空')
        }
        if (!this.profile.nationality?.trim()) {
          validationErrors.push('国籍不能为空')
        }
        if (!this.profile.birthDate?.trim()) {
          validationErrors.push('出生日期不能为空')
        }
        
        // 验证电话号码格式（不能是邮箱格式）
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        
        // 检查电话号码是否包含邮箱特征
        if (this.profile.phone?.trim()) {
          const phoneValue = this.profile.phone.trim()
          
          // 如果包含@符号，说明可能是邮箱地址
          if (phoneValue.includes('@') || emailRegex.test(phoneValue)) {
            validationErrors.push('电话号码字段输入了邮箱地址，请重新输入正确的电话号码')
          }
        }
        
        // 验证邮箱格式
        if (this.profile.email?.trim() && !emailRegex.test(this.profile.email.trim())) {
          validationErrors.push('邮箱格式不正确')
        }

        if (validationErrors.length > 0) {
          return {
            success: false,
            message: `请完善以下信息：${validationErrors.join('、')}`,
            code: 'VALIDATION_ERROR'
          }
        }

        // 日期格式验证和转换
        const validateAndFormatDate = (dateString) => {
          if (!dateString) return ''
          try {
            const date = new Date(dateString)
            if (isNaN(date.getTime())) {
              throw new Error('无效的日期格式')
            }
            // 确保日期格式正确
            const year = date.getFullYear()
            const month = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${year}-${month}-${day}`
                      } catch (error) {
              return dateString
            }
        }


        
        // 构建符合后端格式的数据
        const resumeData = {
          fullName: this.profile.name.trim(),
          xing: this.profile.lastName?.trim() || '',
          ming: this.profile.firstName?.trim() || '',
          nationality: this.profile.nationality.trim(),
          gender: this.profile.gender.trim() === '男' ? 'male' : this.profile.gender.trim() === '女' ? 'female' : 'other',
          dateOfBirth: validateAndFormatDate(this.profile.birthDate),
          phoneNumber: this.profile.phone.trim(),
          email: this.profile.email.trim(),
          wechatWhatsapp: this.profile.wechat?.trim() || '',
          resumeContent: this.experience || '', // 移除trim()，保持原始内容完整
          educationList: this.education.map(edu => ({
            major: edu.major?.trim() || '',
            degree: edu.degree?.trim() || ''
          })).filter(edu => edu.major || edu.degree),
          languagesList: this.languages.filter(lang => lang && typeof lang === 'string' && lang.trim()).map(lang => ({
            languageName: lang.trim()
          })),
          skillsList: this.skills.filter(skill => skill && typeof skill === 'string' && skill.trim())
        }
        
        // 移除空数组，避免后端处理问题
        if (resumeData.educationList.length === 0) {
          delete resumeData.educationList
        }
        if (resumeData.languagesList.length === 0) {
          delete resumeData.languagesList
        }
        if (resumeData.skillsList.length === 0) {
          delete resumeData.skillsList
        }
        
        // 确保所有字符串字段不为null或undefined
        Object.keys(resumeData).forEach(key => {
          if (typeof resumeData[key] === 'string') {
            if (resumeData[key] === null || resumeData[key] === undefined) {
              resumeData[key] = ''
            }
            // 移除字数限制，允许用户输入更长的内容
          }
        })
        
        // 检查必填字段
        const requiredFields = {
          fullName: resumeData.fullName,
          nationality: resumeData.nationality,
          gender: resumeData.gender,
          dateOfBirth: resumeData.dateOfBirth,
          phoneNumber: resumeData.phoneNumber,
          email: resumeData.email
        }
        
        const missingFields = Object.entries(requiredFields)
          .filter(([key, value]) => !value)
          .map(([key]) => key)
        
        if (missingFields.length > 0) {
          return {
            success: false,
            message: `缺少必填字段: ${missingFields.join(', ')}`,
            code: 'VALIDATION_ERROR'
          }
        }
        

        
        // 尝试发送最小数据集，避免复杂字段导致的问题
        // 从fullName中提取xing和ming
        const fullName = resumeData.fullName || ''
        let xing = ''
        let ming = ''
        
        if (fullName) {
          // 如果fullName不为空，尝试分割姓名
          const nameParts = fullName.trim().split(/\s+/)
          if (nameParts.length >= 2) {
            xing = nameParts[0] // 第一个部分作为姓
            ming = nameParts.slice(1).join('') // 剩余部分作为名
          } else {
            // 如果只有一个部分，尝试按中文字符分割
            const trimmedName = fullName.trim()
            if (trimmedName.length >= 2) {
              xing = trimmedName.charAt(0) // 第一个字符作为姓
              ming = trimmedName.substring(1) // 剩余字符作为名
            } else {
              // 如果只有一个字符，全部作为名
              ming = trimmedName
            }
          }
        }
        
        const minimalData = {
          fullName: fullName,
          xing: xing,
          ming: ming,
          nationality: resumeData.nationality || '中国',
          gender: resumeData.gender || 'male',
          dateOfBirth: resumeData.dateOfBirth || '1990-01-01',
          phoneNumber: (resumeData.phoneNumber || '').replace('+86-', ''), // 移除国际前缀
          email: resumeData.email || '',
          resumeContent: this.experience || '', // 直接使用this.experience，确保富文本内容不丢失
          wechatWhatsapp: resumeData.wechatWhatsapp || '', // 添加微信号
          educationList: resumeData.educationList || [], // 添加教育经历
          languagesList: resumeData.languagesList || [], // 添加语言列表
          skillsList: resumeData.skillsList || [] // 添加技能列表
        }
        
        // 数据清理和验证
        Object.keys(minimalData).forEach(key => {
          if (typeof minimalData[key] === 'string') {
            minimalData[key] = minimalData[key].trim()
            // 移除字数限制，允许用户输入更长的内容
          }
        })
        
        console.log('ResumeStore - 准备发送数据到后端:', {
          minimalData,
          fullResumeData: resumeData,
          accessToken: accessToken ? '存在' : '不存在',
          experience: this.experience,
          experienceLength: this.experience ? this.experience.length : 0,
          resumeContent: minimalData.resumeContent,
          resumeContentLength: minimalData.resumeContent ? minimalData.resumeContent.length : 0,
          // 添加更详细的调试信息
          originalExperienceLength: this.experience ? this.experience.length : 0,
          resumeDataResumeContentLength: resumeData.resumeContent ? resumeData.resumeContent.length : 0,
          minimalDataResumeContentLength: minimalData.resumeContent ? minimalData.resumeContent.length : 0
        })
        
        const response = await studentApi.createResume(minimalData)
        
        console.log('ResumeStore - 后端响应:', response)
        
        if (response.code === 200) {
          // 保存成功，同时保存到本地作为备用
          localStorage.setItem('resumeData', JSON.stringify(this.getResumeData))
          console.log('ResumeStore - 简历保存成功')
          return { 
            success: true, 
            message: response.message,
            data: response.data
          }
        } else {
          console.error('ResumeStore - 简历保存失败:', response)
          return { 
            success: false, 
            message: response.message,
            code: response.code
          }
        }
      } catch (error) {
        // 根据错误类型返回不同的错误信息
        let errorMessage = '保存失败，请重试'
        let errorCode = 'UNKNOWN_ERROR'
        
        if (error.response) {
          // 处理响应数据，确保是JSON格式
          let errorData = error.response.data
          const contentType = error.response.headers['content-type'] || error.response.headers['Content-Type'] || ''
          
          // 如果不是JSON格式，尝试解析
          if (!contentType.includes('application/json') && typeof errorData === 'string') {
            try {
              errorData = JSON.parse(errorData)
            } catch (parseError) {
              // 忽略解析错误
            }
          }
          
          switch (error.response.status) {
            case 400:
              // 处理验证错误
              if (errorData && errorData.message) {
                errorMessage = errorData.message
              } else if (errorData && errorData.errors && Array.isArray(errorData.errors)) {
                // 处理字段级别的错误
                const fieldErrors = errorData.errors.map(err => {
                  return err.message || `${err.field}: ${err.message}`
                })
                errorMessage = `数据验证失败：${fieldErrors.join('、')}`
              } else {
                errorMessage = '数据格式错误，请检查填写的信息'
              }
              errorCode = 'VALIDATION_ERROR'
              break
            case 401:
              errorMessage = '登录已过期，请重新登录'
              errorCode = 'AUTH_EXPIRED'
              // 清除过期的token
              localStorage.removeItem('access_token')
              localStorage.removeItem('refresh_token')
              break
            case 500:
              // 处理服务器错误
              if (errorData && errorData.message) {
                errorMessage = `服务器错误：${errorData.message}`
              } else {
                errorMessage = '服务器内部错误，请稍后重试'
              }
              errorCode = 'SERVER_ERROR'
              break
            default:
              errorMessage = error.response.data?.message || '保存失败，请重试'
              errorCode = 'API_ERROR'
          }
        }
      
        // 如果后端保存失败，只保存到本地
        try {
          const data = this.getResumeData
          localStorage.setItem('resumeData', JSON.stringify(data))
        } catch (e) {
          // 忽略本地保存错误
        }
        
        return { 
          success: false, 
          message: errorMessage,
          code: errorCode
        }
      }
    },

    // 重置简历数据
    resetResume() {
      this.profile = {
        firstName: '',
        lastName: '',
        name: '',
        avatar: '',
        nationality: '',
        gender: '',
        birthDate: '',
        city: '',
        country: '',
        phone: '',
        email: '',
        wechat: '',
        desiredPosition: '',
        resumeStatus: '',
        rejectionReason: '',
        lastUpdateTime: ''
      }
      this.education = [{
        major: '',
        degree: '',
        startDate: '',
        endDate: ''
      }]
      this.languages = []
      this.skills = []
      this.experience = ''
      this.personalAdvantages = ''
    },

    // 添加教育经历
    addEducation() {
      // 确保education数组存在
      if (!this.education) {
        this.education = []
      }
      this.education.push({
        major: '',
        degree: '',
        startDate: '',
        endDate: ''
      })
    },

    // 删除教育经历
    removeEducation(index) {
      this.education.splice(index, 1)
      // 确保至少有一个教育经历
      if (this.education.length === 0) {
        this.education.push({
          major: '',
          degree: '',
          startDate: '',
          endDate: ''
        })
      }
    },

    // 添加语言技能
    addLanguage(language) {
      if (language && !this.languages.includes(language)) {
        this.languages.push(language)
      }
    },

    // 删除语言技能
    removeLanguage(language) {
      const index = this.languages.indexOf(language)
      if (index > -1) {
        this.languages.splice(index, 1)
      }
    },

    // 添加技能
    addSkill(skill) {
      if (skill && !this.skills.includes(skill)) {
        this.skills.push(skill)
      }
    },

    // 删除技能
    removeSkill(skill) {
      const index = this.skills.indexOf(skill)
      if (index > -1) {
        this.skills.splice(index, 1)
      }
    },

    // 更新工作经验
    updateExperience(content) {
      this.experience = content
    },



    // 验证简历数据
    validateResume() {
      const errors = []
      
      // 检查姓名：要么填写姓和名，要么填写中文姓名
      if (!this.profile.lastName && !this.profile.firstName && !this.profile.name) {
        errors.push('请输入姓和名，或中文姓名')
      }
      
      if (!this.profile.phone) {
        errors.push('请输入电话')
      }
      
      if (!this.profile.email) {
        errors.push('请输入邮箱')
      }
      
      if (this.education.length === 0 || !this.education[0].major) {
        errors.push('请至少填写一项教育经历')
      }
      
      if (this.languages.length === 0 && this.skills.length === 0) {
        errors.push('请至少填写一项语言或技能')
      }
      
      return {
        isValid: errors.length === 0,
        errors
      }
    },

    // 导出简历数据
    exportResume() {
      return this.getResumeData
    },

    // 导入简历数据
    importResume(data) {
      if (data.profile) {
        this.profile = { ...this.profile, ...data.profile }
      }
      if (data.education) {
        this.education = [...data.education]
      }
      if (data.languages) {
        this.languages = [...data.languages]
      }
      if (data.skills) {
        this.skills = [...data.skills]
      }
      if (data.experience) {
        this.experience = data.experience
      }
      if (data.personalAdvantages) {
        this.personalAdvantages = data.personalAdvantages
      }
    },

    // 获取简历状态
    async getResumeStatus() {
      try {
        const response = await studentApi.getResumeStatus()
        return response.data
      } catch (error) {
        return null
      }
    },

    // 提交简历审核
    async submitResume() {
      try {
        const response = await studentApi.submitResume()
        
        // 检查响应格式
        if (response && response.code === 200) {
          return true
        } else if (response && response.success) {
          return true
        } else {
          return false
        }
      } catch (error) {
        return false
      }
    },

    // 删除简历
    async deleteResume() {
      try {
        const response = await studentApi.deleteResume()
        if (response.success) {
          this.resetResume()
          localStorage.removeItem('resumeData')
        }
        return response.success
      } catch (error) {
        return false
      }
    }
  }
}) 